<template>
  <div class="funding-source-container">
    <!-- 搜索栏 -->
    <el-card class="search-container" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="公司名称/法人名称/电话" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 240px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增出资方</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>出资方列表</span>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="company_name" label="公司名称" min-width="150" />
        <el-table-column prop="legal_person" label="法人名称" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column label="资金额度" width="150" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.fund_amount) }}
          </template>
        </el-table-column>
        <el-table-column label="已用额度" width="150" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.used_amount) }}
          </template>
        </el-table-column>
        <el-table-column label="可用额度" width="150" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.available_amount) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status === 1 ? 'danger' : 'success'" size="small"
              @click="handleStatusChange(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="650px" :close-on-click-modal="false">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="公司名称" prop="company_name">
          <el-input v-model="formData.company_name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="法人名称" prop="legal_person">
          <el-input v-model="formData.legal_person" placeholder="请输入法人名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="资金额度" prop="fund_amount">
          <el-input-number v-model="formData.fund_amount" :min="0" :step="10000" controls-position="right"
            :precision="2" style="width: 240px;" />
          <span class="form-item-unit">元</span>
        </el-form-item>
        <template v-if="!isEdit">
          <el-form-item label="账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { getInvestorList, createInvestor, updateInvestor, updateInvestorStatus } from '@/api/investor';
import type { Investor, InvestorCreateRequest, InvestorUpdateRequest } from '@/api/investor';
import { formatDate } from '@/utils/format';

defineOptions({
  name: "FundingSourceList"
});

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '启用', value: 1 },
  { label: '禁用', value: 2 }
];

// 表格数据
const loading = ref(false);
const tableData = ref<Investor[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增出资方');
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const isEdit = ref(false);

// 表单数据
const formData = reactive<InvestorCreateRequest & { id?: number }>({
  company_name: '',
  legal_person: '',
  phone: '',
  fund_amount: 0,
  username: '',
  password: '',
});

// 表单验证规则
const formRules = reactive<FormRules>({
  company_name: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  legal_person: [
    { required: true, message: '请输入法人名称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
});

// 加载列表数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchForm.keyword,
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      status: searchForm.status ? Number(searchForm.status) : undefined
    };

    const res = await getInvestorList(params);
    if (res.code === 0) {
      tableData.value = res.data.list;
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取出资方列表失败', error);
    ElMessage.error('获取出资方列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
};

// 格式化状态
const formatStatus = (status: number) => {
  return status === 1 ? '启用' : '禁用';
};

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  return formatDate(new Date(datetime), 'YYYY-MM-DD HH:mm:ss');
};

// 获取状态标签类型
const getStatusType = (status: number) => {
  return status === 1 ? 'success' : 'danger';
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadData();
};

// 重置查询
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  handleSearch();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadData();
};

// 新增出资方
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = '新增出资方';

  // 重置表单
  formData.id = undefined;
  formData.company_name = '';
  formData.legal_person = '';
  formData.phone = '';
  formData.fund_amount = 0;
  formData.username = '';
  formData.password = '';

  dialogVisible.value = true;
};

// 编辑出资方
const handleEdit = (row: Investor) => {
  isEdit.value = true;
  dialogTitle.value = '编辑出资方';

  // 填充表单数据
  formData.id = row.id;
  formData.company_name = row.company_name;
  formData.legal_person = row.legal_person;
  formData.phone = row.phone;
  formData.fund_amount = row.fund_amount;

  dialogVisible.value = true;
};

// 更改状态
const handleStatusChange = async (row: Investor) => {
  const action = row.status === 1 ? '禁用' : '启用';

  try {
    await ElMessageBox.confirm(`确认要${action}该出资方吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const newStatus = row.status === 1 ? 2 : 1;
    const res = await updateInvestorStatus({
      id: row.id,
      status: newStatus
    });

    if (res.code === 0) {
      ElMessage.success(`${action}成功`);
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res.message || `${action}失败`);
    }
  } catch (error) {
    console.log('用户取消操作');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;

      try {
        if (isEdit.value) {
          // 更新出资方
          const updateData: InvestorUpdateRequest = {
            id: formData.id!,
            company_name: formData.company_name,
            legal_person: formData.legal_person,
            phone: formData.phone,
            fund_amount: formData.fund_amount
          };

          const res = await updateInvestor(updateData);
          if (res.code === 0) {
            ElMessage.success('更新成功');
            dialogVisible.value = false;
            loadData(); // 重新加载数据
          } else {
            ElMessage.error(res.message || '更新失败');
          }
        } else {
          // 创建出资方
          const createData: InvestorCreateRequest = {
            company_name: formData.company_name,
            legal_person: formData.legal_person,
            phone: formData.phone,
            fund_amount: formData.fund_amount,
            username: formData.username,
            password: formData.password
          };

          const res = await createInvestor(createData);
          if (res.code === 0) {
            ElMessage.success('创建成功');
            dialogVisible.value = false;
            loadData(); // 重新加载数据
          } else {
            ElMessage.error(res.message || '创建失败');
          }
        }
      } catch (error) {
        console.error('提交表单失败', error);
        ElMessage.error('操作失败，请稍后重试');
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.funding-source-container .search-container {
  margin-bottom: 20px;
}

.funding-source-container .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.funding-source-container .pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-item-unit {
  margin-left: 8px;
  color: #606266;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: var(--el-text-color-primary);
  font-weight: 500;
}
</style>